package com.tzy.gateway.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
 * Redis服务;还需要有redis配置类 RedisConfig
 */
@Service
@Slf4j
public class RedisService extends MessageListenerAdapter {
//    @Resource
//    private ReactiveRedisTemplate reactiveRedisTemplate;

//    public void run(String... args) throws Exception {
//        reactiveRedisTemplate
//                .opsForValue()
//                .set("name", "李四")
//                .subscribe(b -> log.info("set result:{}", b),
//                        e -> log.error("set data error:{}", e));
//    }


    @Resource(name = "objectRedisTemplate")
    private RedisTemplate<String,Object> objectRedisTemplate;

    /**
     * 设置值
     * @param key
     * @param value
     * @param second 过期时间:单位秒
     */
    public void setString(String key,String value,int second){
        objectRedisTemplate.opsForValue().set(key,value,second,TimeUnit.SECONDS);
    }
    /**
     * 获取值
     * @param key
     * @return
     */
    public String getString(String key){
        Object o = objectRedisTemplate.opsForValue().get(key);
        if(o==null)
            return null;
        return (String)o;
    }
    public void setObject(String key,Object obj){
        objectRedisTemplate.opsForValue().set(key,obj);
    }

    public <T> T getObject(String key){
        Object o = objectRedisTemplate.opsForValue().get(key);
        return (T)o;
    }

    public <T extends Object> T getObject(String key,Class clazz){
        Object o = objectRedisTemplate.opsForValue().get(key);
        if(o == null)return null;
        if(clazz.isInstance(o))
        if(o.getClass().getName().equalsIgnoreCase(clazz.getName())){
            return (T)o;
        }
        log.error("{}的值不是{}的实例",key,clazz.getName());
        return null;
    }
    /**
     * 自增1
     * @param key
     * @return
     */
    public Long incr(String key){
        Long increment = objectRedisTemplate.opsForValue().increment(key);
        return increment;
    }

    /**
     * redis订阅消息处理
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
//        super.onMessage(message, pattern);
        log.info("channel:{} message:{}",new String(message.getChannel()),new String(message.getBody()));
    }
}
